package com.chen.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.springboot.common.Result;
import com.chen.springboot.entity.Address;
import com.chen.springboot.mapper.AddressMapper;
import com.chen.springboot.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;


@RestController
@RequestMapping("/address")
public class AddressController {

    @Resource
    private AddressMapper addressMapper;
    @Autowired
    private UserMapper userMapper;

    // 通过 userid 来查询所有地址
    @GetMapping
    public Result<?> getPage(@RequestParam(defaultValue = "1") Integer pageNum,
                             @RequestParam(defaultValue = "10") Integer pageSize,
                             @RequestParam Integer userId) {
        Page<Address> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Address> wrapper = Wrappers.lambdaQuery();
        // 查询当前的 userId
        wrapper.eq(Address::getUserId, userId);
        page = addressMapper.selectPage(page, wrapper);
        return Result.success(page);
    }

    // 新增地址
    @PostMapping
    public Result<?> add(@RequestBody Address address) {
        if (addressMapper.insert(address) == 0)
            return Result.error("400", "新增地址插入失败");
        else
            return Result.success();
    }

    //删除单个地址
    @DeleteMapping("{id}")
    public Result<?> deleteByPath(@PathVariable Integer id) {
        if (addressMapper.deleteById(id) == 0)
            return Result.error("400", "删除地址失败");
        else
            return Result.success();
    }

    //删除所有地址
    @DeleteMapping("/all")
    public Result<?> deleteAll() {
        if (addressMapper.delete(null) == 0)
            return Result.error("400", "删除地址失败");
        else
            return Result.success();
    }

    // 更新地址
    @PutMapping
    public Result<?> update(@RequestBody Address address) {
        if (addressMapper.updateById(address) == 0)
            return Result.error("400", "更新地址失败");
        else
            return Result.success();
    }

    //更改地址状态
    @GetMapping("/update")
    public Result<?> updateById(@RequestParam Integer id,@RequestParam Integer userId) {
        addressMapper.update0();
        if (addressMapper.update1(id)) {
            return Result.success();
        } else {
            return Result.error("400", "更改状态失败");
        }
    }

    //查询选择的地址
    @GetMapping("/one")
    public Result<?> getOne(@RequestParam Integer userId) {
            return Result.success(addressMapper.getOne(userId));
    }
}
